import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    organizations: [],
  },
  getters: {    
  },  
  //https://vuex.vuejs.org/guide/mutations.html#commit-with-payload
  mutations: {//Mutations Must Be Synchronous
    saveOrganization(currentState, organization) {
      let index = currentState.organizations.findIndex(p => p.id == organization.id);
      if (index == -1) {
          currentState.organizations.push(organization);
      } else {
          Vue.set(currentState.organizations, index, organization);
      }
    },
    deleteOrganization(currentState, organization) {
        let index = currentState.organizations.findIndex(p => p.id == organization.id);
        currentState.organizations.splice(index, 1);
    }    
  },
  //https://vuex.vuejs.org/guide/actions.html#dispatching-actions
  actions: {
    async getOrganizationsAction(context) {
      // (await Axios.get(baseUrl)).data.forEach(p => context.commit("saveOrganization", p));
    },
    async saveOrganizationAction(context, organization) {
        // let index = context.state.organizations.findIndex(p => p.id == organization.id);
        // if (index == -1) {
        //     await Axios.post(baseUrl, organization);
        // } else {
        //     await Axios.put(`${baseUrl}${organization.id}`, organization);
        // }
        context.commit("saveOrganization", organization);
    },
    async deleteOrganizationAction(context, organization) {
        // await Axios.delete(`${baseUrl}${organization.id}`);
        context.commit("deleteOrganization", organization);
    }    
  }
});
